<style>
    .amap-icon img,
    .amap-marker-content img{
        width: 25px;
        height: 34px;
    }
    .suggestionList {
        list-style-type: none;
        padding: 0;
        margin: 0;
        position: absolute;
        left: 0;
        top: 30px;
        height: 400px;
        overflow-y: auto;
    }
    .suggestionList::-webkit-scrollbar {
        width: 10px;
        height: 10px;
        background-color: #fafafa;
    }
    .suggestionList::-webkit-scrollbar-thumb {
        background-color: #cacaca;
        border-radius: 0.4rem;
    }


    .suggestionList li a {
        margin-top: -1px;
        /*background-color: #f6f6f6;*/
        text-decoration: none;
        font-size: 18px;
        color: black;
        display: block;
    }

    .suggestionList li .item_info{
        font-size: 12px;
        color:grey;

    }

    .suggestionList li a:hover:not(.header) {
        background-color: #eee;
    }
</style>
<div id="tencent-address">
    <div class="{{$viewClass['form-group']}}">
        <div class="form-group row form-field"></div>
        <label class="{{$viewClass['label']}} control-label">{!! $label !!}</label>
        <div class="{{$viewClass['field']}}">
            @include('admin::form.error')
            <div class="{{ $class }}" style="position: relative;">
                <div class="form-map" style="width: 100%;height: {{ $height }}"></div>
                <div class="input-group input-group-sm" style="position: absolute; left: 20px;top: 10px;z-index:99999;width: 300px">
                    <input type="text"  value="" class="form-control searchKeyword" placeholder="搜索地址" list="{{ $name['address'] }}_addressList" />
                    <ul class="suggestionList list-group" id="{{ $name['address'] }}_addressList"></ul>
                </div>
                <input type="hidden" class="form-lat" name="{{ $name['lat'] }}" value="{{ $value['lat'] ?? null }}" {!! $attributes !!} />
                <input type="hidden" class="form-lng" name="{{$name['lng']}}" value="{{ $value['lng'] ?? null }}" {!! $attributes !!} />
            </div>
            @include('admin::form.help-block')
        </div>
    </div>
    <div class="form-group row form-field">
        <div class="col-md-2 text-capitalize control-label">
            <span>详细地址</span>
        </div>
        <div class="col-md-8 ">
            <div class="help-block with-errors"></div>
            <div class="input-group">
                <span class="input-group-prepend"><span class="input-group-text bg-white"><i class="feather icon-edit-2"></i></span></span>
                <input type="text" id="form-address" name="{{ $name['address'] }}" value="{{ $value['address'] ?? null }}" class="form-control form-address field_address _normal_" placeholder="输入 详细地址" list="{{ $name['address'] }}_addressList" />
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="mapPage">

</script>
<script init="#tencent-address">
    var lat = $this.find('.form-lat'),
        lng = $this.find('.form-lng'),
        form_address = $this.find('.form-address'),
        container = $this.find('.form-map'),
        mapId = "_" + Dcat.helpers.random(),
        now_layer;
    container.attr('id', mapId);
    let searchKeywordDom = $this.find('.searchKeyword')
    let addressList = $this.find("#{{ $name['address'] }}_addressList");

    @if($type === 'tencent')
    var map,marker,infoWin,geocoder;

    const setMapCenter = function (lat,lng){
        return new TMap.LatLng(lat,lng)
    }

    function initTencentMap() {
        var init = function (){
            //定义地图中心点坐标
            var center = setMapCenter(lat.val()||39.905434998537224, lng.val()||116.39194735516048)
            //定义map变量，调用 TMap.Map() 构造函数创建地图
            map = new TMap.Map(container[0], {
                center: center,//设置地图中心点坐标
                zoom: 18,   //设置地图缩放级别
                // pitch: 43.5,  //设置俯仰角
                // rotation: 45    //设置地图旋转角度
            });

            //创建并初始化MultiMarker
            marker = new TMap.MultiMarker({
                map: map,  //指定地图容器
                //样式定义
                styles: {
                    //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
                    "myStyle": new TMap.MarkerStyle({
                        "width": 25,  // 点标记样式宽度（像素）
                        "height": 35, // 点标记样式高度（像素）
                        "anchor": { x: 16, y: 32 }
                    })
                },
                //点标记数据数组
                geometries: [{
                    "id": "1",   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                        "styleId": 'myStyle',  //指定样式id
                        "position": center,  //点标记坐标位置
                        "properties": {//自定义属性
                            "title": "marker1"
                        }
                    }
                ]
            });

            infoWin = new TMap.InfoWindow({
                map:map,
                position: center,
                offset: { x: 0, y: -32 }
            });

            geocoder = new TMap.service.Geocoder({
                complete: function (result) {
                    console.log(result)
                    var location = result.detail.location
                    infoWin.open();

                    form_address.val(address)
                    // infoWin.setPosition(center);//设置信息窗位置
                }
            });

            const handleResult = (result,center)=>{
                const component = result.address_component
                let address = component.province + component.city + component.district;
                if(component.street_number){
                    address += component.street_number;
                }else{
                    address += component.street;
                }
                marker.updateGeometries([{
                    "styleId":"myStyle",
                    "id": 1,
                    "position": center
                }])
                map.setCenter(center);
                form_address.val(address)
                infoWin.setPosition(center);//设置信息窗内容
                infoWin.setContent(address);//设置信息窗内容
                infoWin.open()
            }

            const setMarkerGeoCoderAddress = function (center){
                geocoder.getAddress({location: center}).then(({ result })=>{
                    handleResult(result, center)
                })
            }
            let Suggestion = new TMap.service.Suggestion({pageSize:20})

            setMarkerGeoCoderAddress(center)

            var clickHandler = function (evt) {
                var latLng = evt.latLng
                lat.val(latLng.lat);
                lng.val(latLng.lng);
                const center = setMapCenter(latLng.lat,latLng.lng);
                setMarkerGeoCoderAddress(center)
            }
            map.on("click", clickHandler)
            function eventOff(){
                map.off("click", clickHandler)
            }
            const search = function (){
                if(searchKeywordDom.val()){
                    Suggestion.getSuggestions({
                        keyword: searchKeywordDom.val()
                    }).then(({ data })=>{
                        $(addressList).html();
                        let option = []
                        data?.forEach((item)=>{
                            let location = item.location
                            option.push(`<li class="list-group-item" ><a href="#" onclick="setSuggestion(${location.lat},${location.lng})">${item.title}<span class="item_info">${item.address}</span></a></li>`)
                        })
                        $(addressList).html(option.join(""))
                        $(addressList).show()
                    })
                }
            }
            $(document).on('input','.searchKeyword',function (){
                search()
            })

            window.setSuggestion = function (lat1,lng1){
                var center = setMapCenter(lat1,lng1)
                setMarkerGeoCoderAddress(center)
                lat.val(lat1);
                lng.val(lng1);
                $(addressList).hide()
                searchKeywordDom.val("")
            }
        }
        init();
    }

    initTencentMap();

@endif
</script>
